<html>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<title>Section 15.1.&nbsp; Validating User Input with JavaScript</title>
<link rel="STYLESHEET" type="text/css" href="images/style.css">
<link rel="STYLESHEET" type="text/css" href="images/docsafari.css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-15.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-15-SECT-2.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<br><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><TD valign="top"><a name="learnphpmysql-CHP-15-SECT-1"></a>
<h3 id="title-IDAUHCWC" class="docSection1Title">15.1. Validating User Input with JavaScript</h3>
<a name="IDX-CHP-15-0662"></a> 
<a name="IDX-CHP-15-0663"></a> 
<a name="IDX-CHP-15-0664"></a> 

<p class="docText">On the client side, your best tool for validating data is JavaScript. JavaScript is different than PHP, because it's designed to execute in the user's browser instead of on the server. Because it executes in the client's computer, JavaScript is not allowed to access anything that could be a security risk, such as the local filesystem or network resources. JavaScript is primarily used in web pages. Although its name sounds like Java, it has no relationship to it.</p>
<p class="docText">Since this processing is built into most modern browsers, it's not difficult for end users to disable it. Therefore, even when you use JavaScript, always take precautions to handle the possibility of it not being present on the browser.</p>
<p class="docText">Some of the practical things you can do with JavaScript are checking fields and alerting the user to a problem before the data is submitted to the server. The validation can be as simple as checking for an empty field or more complex checks such as validating an email address.</p>
<p><table border="0" bgcolor="black" cellspacing="0" cellpadding="1" width="90%" align="center"><tr><td><table bgcolor="white" width="100%" border="0" cellspacing="0" cellpadding="6"><tr><td width="60" valign="top"><img src="images/warning_yellow.jpg" width="51" height="36" alt=""></td><td valign="top">
<p class="docText">Although JavaScript provides immediate feedback to a user if a field doesn't pass validation, it shouldn't be relied upon as the only validation method. Your PHP code should always perform the final validation.</P>
</td></tr></table></TD></TR></table></p><BR>
<p class="docText">JavaScript has many functions built in for validating fields. They range from the familiar length function to more complex and powerful <span class="docEmphasis">regular expressions</span>. We'll discuss regular expressions in more detail later. For now, all you need to know is that they provide a way of concisely describing what a string should look like. For example, an email address should have an at (@) sign with alphanumeric characters before and after it, such as <a class="docLink" href="mailto:michele@krautgrrl.com">michele@krautgrrl.com</a>.</p>
<p class="docText">There is one non-JavaScript tactic you can use to reduce client-side errors. You can set the <tt>MAXLENGTH</tt> attribute in your form's text fields. This prevents users from entering strings that are too large.</p>
<p class="docText">Let's go ahead and work with <a class="docLink" href="#learnphpmysql-CHP-15-EX-1">Example 15-1</a>, which validates before submission.</p>
<a name="learnphpmysql-CHP-15-EX-1"></a><H5 id="title-IDAMJCWC" class="docExampleTitle">Example 15-1. Building a form that validates its fields before submission</h5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
&lt;SCRIPT LANGUAGE="JavaScript1.2" SRC="source.js"&gt;
&lt;/SCRIPT&gt;

&lt;HTML&gt;
&lt;HEAD&gt;
    &lt;TITLE&gt;Sample Form&lt;/TITLE&gt;
&lt;/HEAD&gt;

&lt;SCRIPT LANGUAGE="JavaScript1.2"&gt;
    function check_valid(form) {
    var error = "";
    error += verify_username(form.username.value);
    error += verify_password(form.password.value);
    error += verify_phone(form.phone.value);
    error += verify_email(form.email.value);
    if (error != "") {
       alert(error);
       return false;
    }
return true;
}
&lt;/SCRIPT&gt;

&lt;BODY BGCOLOR="#FFFFFF"&gt;
    &lt;FORM action="process.php" METHOD="post"
onSubmit="return check_valid(this)" id="test1" name="test1"&gt;
    &lt;TABLE BORDER="0" WIDTH="100%" CELLSPACING="0" CELLPADDING="0"&gt;
        &lt;TR&gt;
            &lt;TD WIDTH="30%" ALIGN="right"&gt;Username&lt;/TD&gt;
            &lt;TD WIDTH="70%"&gt;: &lt;INPUT TYPE="text" NAME="username"&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
            &lt;TD ALIGN="right"&gt;Password&lt;/TD&gt;
            &lt;TD&gt;: &lt;INPUT TYPE="password" NAME="password"&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
            &lt;TD ALIGN="right"&gt;Phone&lt;/TD&gt;
            &lt;TD&gt;: &lt;INPUT TYPE="phone" NAME="phone"&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
            &lt;TD ALIGN="right"&gt;Email&lt;/TD&gt;
            &lt;TD&gt;: &lt;INPUT TYPE="email" NAME="email"&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
            &lt;TD&gt;&amp;nbsp;&lt;/TD&gt;
            &lt;TD&gt;&lt;INPUT TYPE="SUBMIT" VALUE="Submit"&gt;&lt;/TD&gt;
        &lt;/TR&gt;
    &lt;/TABLE&gt;
    &lt;/FORM&gt;
&lt;/BODY&gt;
&lt;/HTML&gt;
</pre><BR>

</TD></tr></table></P>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-15-EX-1">Example 15-1</a> includes the JavaScript in <a class="docLink" href="#learnphpmysql-CHP-15-EX-2">Example 15-2</a>. The <tt>SRC=</tt> tag within the <tt>SCRIPT</tt> element includes the script that makes the functions available within the HTML source file.</p>
<a name="learnphpmysql-CHP-15-EX-2"></a><h5 id="title-IDAFKCWC" class="docExampleTitle">Example 15-2. The file source.js contains functions to check the various fields</H5><P><table cellspacing="0" width="90%" border="1" cellpadding="5"><tr><td>

<pre>
// verify username - 610 chars, uc, lc, and underscore only.
function verify_username (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a username.\n";
}
    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if ((strng.length &lt; 6) || (strng.length &gt; 10)) {
       error = "The username is the wrong length. It must be 6-10 characters.\n";
    }
    else if (illegalChars.test(strng)) {
    error = "The username contains illegal characters.\n";
    }
return error;
}

// verify password - between 68 chars, uppercase, lowercase, and numeral
function verify_password (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a password.\n";
}
    var illegalChars = /[\W_]/; // allow only letters and numbers
    if ((strng.length &lt; 6) || (strng.length &gt; 8)) {
       error = "The password is the wrong length. It must be 68 characters.\n";
    }
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";
    }
    else if (!((strng.search(/(a-z)+/)) &amp;&amp; (strng.search(/(A-Z)+/)) &amp;&amp;
(strng.search(/(0-9)+/)))) {
       error = "The password must contain at least one uppercase letter, one
lowercase letter, and one numeral.\n";
    }
return error;
}

// verify email
function verify_email (strng) {
var error="";
if (strng == "") {
   error = "You didn't enter an email address.\n";
}

    var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strng))) {
       error = "Please enter a valid email address.\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\&lt;\&gt;\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "The email address contains illegal characters.\n";
       }
    }
return error;
}

// verify phone number - strip out delimiters and verify for 10 digits
function verify_phone (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a phone number.\n";
}
//strip out acceptable non-numeric characters
var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');
    if (isNaN(parseInt(stripped))) {
       error = "The phone number contains illegal characters.";

    }
    if (!(stripped.length == 10)) {
    error = "The phone number is the wrong length. Make sure you included an area
code.\n";
    }
return error;
}
</pre><br>

</td></TR></table></p>
<p class="docText"><a class="docLink" href="#learnphpmysql-CHP-15-FIG-1">Figure 15-1</a> shows a form with some invalid data, and <a class="docLink" href="#learnphpmysql-CHP-15-FIG-2">Figure 15-2</a> shows the result.</P>
<a name="learnphpmysql-CHP-15-FIG-1"></a><p><center>
<h5 class="docFigureTitle">Figure 15-1. Entering some invalid data into the form</H5>
<img border="0" alt="" width="549" height="199" SRC="images/learnphpmysql_1501.jpg">
</center></P><br>
<a name="learnphpmysql-CHP-15-FIG-2"></a><P><center>
<h5 class="docFigureTitle">Figure 15-2. The JavaScript alert window lists the validation problems</h5>
<img border="0" alt="" width="451" height="157" SRC="images/learnphpmysql_1502.jpg">
</center></p><br>

<a href="11011536.html"><img src="images/pixel.jpg" alt="" width="1" height="1" border="0"></a></TD></TR></table>
<br>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-15.html><img src="images/prev.gif" width="60" height="17" border="0" align="absmiddle" alt="Previous Page"></a>
<td align="right"><div STYLE="MARGIN-LEFT: 0.15in;">
<a href=learnphpmysql-CHP-15-SECT-2.html><img src="images/next.gif" width="60" height="17" border="0" align="absmiddle" alt="Next Page"></a>
</div></td></tr></table>
<script type="text/javascript"><!--
google_ad_client = "pub-0203281046321155";
google_alternate_ad_url = "http://www.bookhtml.com/adbrite.htm";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="4867465545";
google_color_border = "FFFFFF";
google_color_link = "0000FF";
google_color_bg = "FFFFFF";
google_color_text = "000000";
google_color_url = "0000FF";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</html>
